//
//  HYCustomTextView.m
//  HYRefresh
//
//  Created by HYMac on 16/3/14.
//  Copyright © 2016年 HYMac. All rights reserved.
//

#import "HYCustomTextView.h"
#import <CoreText/CoreText.h>
@implementation HYCustomTextView
-(NSArray *)fontArray
{
    if (_fontArray==nil)
    {
        _fontArray=[UIFont familyNames];
    }
    return _fontArray;
}

-(void)setHYtext:(NSString *)HYtext
{
    _HYtext=HYtext;
   
    [self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect
{
        
    if (self.HYtext)
    {
         [self drawText];
    }
   }
-(const char *)translateString:(NSString *)str
{
    const char *resultString=[str UTF8String];
    return resultString;
}
-(void)drawText
{
   
       NSMutableAttributedString * mabString = [[NSMutableAttributedString alloc]initWithString:self.HYtext];
    [mabString beginEditing];
   //const char *result="Thonburi";
    //CFSTR()
    CTFontRef font = CTFontCreateWithName(CFSTR("SnellRoundhand"), 17, NULL);
    [mabString addAttribute:(id)kCTFontAttributeName value:(__bridge id _Nonnull)(font) range:NSMakeRange(0, [self.HYtext length])];
    [mabString addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor grayColor].CGColor range:NSMakeRange(0, self.HYtext.length)];

    [mabString endEditing];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)mabString);
    //2.给一个路径对象（用来封装文本坐标位置等）
    CGMutablePathRef path = CGPathCreateMutable();
    
    //3.给个显示字符串的坐标范围,x越大，文字越右边
    CGPathAddRect(path, NULL, CGRectMake(0, -5, 90, 40));
    //4.建立字符串的画布
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    //5.获取当前view的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //6.用上面的创建的设置来设置文本矩阵
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    
    //7.保存现在的上下文状态，后续的操作不会影响到现在的屏幕
    CGContextSaveGState(context);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextTranslateCTM(context, 1.0, -self.frame.size.height);
    CTFrameDraw(frame, context);
    
    //释放
    CGPathRelease(path);
    CFRelease(frameSetter);
    
}
@end
